package com.tfswx.ruleengine.compute.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tfswx.ruleengine.compute.exception.AppException;

import java.util.List;

/**
 * @author Ricky
 * @date 2021/6/9
 */
public class TyywHttpUtil {
    private TyywHttpUtil() {
    }


    private static final String SUCCESS_FIELD = "success";
    private static final String MESSAGE_FIELD = "message";
    private static final String DATA_FIELD = "data";

    public static <T> T getObject(JSONObject response, Class<T> clazz) {
        boolean success = response.getBooleanValue(SUCCESS_FIELD);
        if (!success) {
            throw new AppException(response.getString(MESSAGE_FIELD));
        }
        JSONObject jsonObject = response.getJSONObject(DATA_FIELD);
        return jsonObject != null ? jsonObject.toJavaObject(clazz) : null;
    }

    public static <T> List<T> getList(JSONObject response, Class<T> clazz) {
        boolean success = response.getBooleanValue(SUCCESS_FIELD);
        if (!success) {
            throw new AppException(response.getString(MESSAGE_FIELD));
        }
        JSONArray jsonArray = response.getJSONArray(DATA_FIELD);
        return jsonArray != null ? jsonArray.toJavaList(clazz) : null;
    }

    public static int getInteger(JSONObject response) {
        boolean success = response.getBooleanValue(SUCCESS_FIELD);
        if (!success) {
            throw new AppException(response.getString(MESSAGE_FIELD));
        }
        return response.getIntValue(DATA_FIELD);
    }
}
